﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Text;
using System.IO;
using System.Web;
using ANGFLib;

namespace AngfWebPlayer3.Controllers
{
    public class AddCommandPacket
    {
        public string urls;
        public bool checkOnly;
    }

    public class AddResponsePacket
    {
        public bool success;
        public string html;
    }

    public class AddUrlsApiController : ApiController
    {
        public AddResponsePacket Post(/*[FromBody]*/AddCommandPacket value)
        {
            var sb = new StringBuilder();
            var reader = new StringReader(value.urls);
            var client = new WebClient();
            var list = new List<MyXmlDoc>();
            var context = new AngfWebPlayer3.Models.MvcBasicContext();
            for (; ; )
            {
                var uri0 = reader.ReadLine();
                if (uri0 == null) break;
                var uri = uri0.Trim();
                Stream stream;
                try
                {
                    stream = client.OpenRead(uri.Trim());
                    var doc = Scenarios.LoadMyXmlDocFromNet(stream, new Uri(uri));
                    if (doc == null)
                    {
                        sb.AppendFormat("<p>{0}はモジュールとして使用できません。</p>", HttpUtility.HtmlEncode(uri));
                    }
                    else
                    {
                        sb.AppendFormat("<p>{0}は{1}として使用できます。</p>", HttpUtility.HtmlEncode(uri), HttpUtility.HtmlEncode(doc.name));
                        list.Add(doc);
                        if (!value.checkOnly)
                        {
                            var entity = new ScenarioRecord();
                            entity.Id = doc.id;
                            entity.ModuleUri = uri;
                            entity.Comment = doc.name;
                            context.SchenarioRecords.Add(entity);
                            sb.AppendFormat("<p>{0}をモジュールとして追加しました。</p>", HttpUtility.HtmlEncode(uri));
                        }
                    }
                }
                catch (Exception e)
                {
                    sb.AppendFormat("<p>{0}</p>", HttpUtility.HtmlEncode(e.ToString()));
                }
            }
            if (!value.checkOnly && list.Count > 0) context.SaveChanges();
            return new AddResponsePacket() { success = list.Count > 0, html = sb.ToString() };
        }
    }
}
